<?php

namespace app\api\controller;

use app\common\logic\Data;
use think\facade\Validate;
use think\facade\Db;
use app\lib\Result;

class ShortUrl extends Base
{
  /**
   * 列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|url', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('short_url')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('short_url')->where($where)->count('_id');
    $appIds = [];
    foreach ($dataList as $key => $vo) {
      $appIds[] = $vo['_id'];
    }
    $whereTj[] = ['uid', '=', $this->uid];
    $whereTj[] = ['s_id', 'in', $appIds];
    $yesterday = date('Ymd', time() - 86400);
    $whereTj[] = ['date', '=', $yesterday];
    $yestData = Db::connect('mongodb')->name('short_url_log')->where($whereTj)->select();
    if (!empty($yestData)) {
      $yestData = $yestData->toArray();
    }
    $yestItem = [];
    foreach ($yestData as $key => $vo) {
      if (!isset($yestItem[$vo['s_id']]['pv'])) {
        $yestItem[$vo['s_id']]['pv'] = 0;
      }
      $yestItem[$vo['s_id']]['pv'] = $yestItem[$vo['s_id']]['pv'] + $vo['pv'];
      if (!isset($yestItem[$vo['s_id']]['uv'])) {
        $yestItem[$vo['s_id']]['uv'] = 0;
      }
      $yestItem[$vo['s_id']]['uv'] = $yestItem[$vo['s_id']]['uv'] + $vo['uv'];
    }
    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['expire'] = strval($vo['expire']);
      if ($vo['expire_time'] === 99999) {
        $vo['expire_time'] = '长期';
        $vo['status'] = 1;
      } else {
        if ($vo['expire_time'] > time()) {
          $vo['status'] = 1;
        } else {
          $vo['status'] = -1;
        }
        $vo['expire_time'] = date('Y-m-d H:i:s', $vo['expire_time']);
      }
      $vo['yesterday_pv'] = 0;
      $vo['yesterday_uv'] = 0;
      if (isset($yestItem[$vo['_id']])) {
        $vo['yesterday_pv'] = $yestItem[$vo['_id']]['pv'];
        $vo['yesterday_uv'] = $yestItem[$vo['_id']]['uv'];
      }
    }
    $returnData['data']['data'] = $dataList;
    $returnData['data']['totalCount'] = $totalcount;
    $returnData['data']['pageNo'] = (int) $data['pageNo'];
    $returnData['data']['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData['data']);
  }
  /**
   * 编辑文章
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function editItemInfo()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|max:32',
        'expire|有效期'  => 'require|number',
        'url_type|链接类型'  => 'require|number',
      ];
      $data = [
        'title' => input('param.title', '', 'trim'),
        'url' => input('param.url', '', 'trim'),
        'expire' => input('param.expire', '', 'trim'),
        'url_type' => input('param.url_type', '', 'trim'),
        'ma_id' => input('param.ma_id', '', 'trim'),
        'page' => input('param.page', '', 'trim'),
        '_id' => input('param._id', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Error($validate->getError());
      }
      $data['url_type'] = (int)$data['url_type'];
      if ($data['url_type'] == 1 && !Data::isValidUrl($data['url'])) {
        return Result::Error('请输入正确的源链地址');
      }
      if ($data['url_type'] == 2 && empty($data['ma_id'])) {
        return Result::Error('请选择微信小程序');
      }
      $UrlCount = Db::connect('mongodb')->name('short_url')->count();
      $this->security::checkVersionLimit($this->user['version'], 'short_url_num', '短链接数量', $UrlCount);
      $data['expire_time'] = (int) $data['expire'];
      if ($data['expire'] != '99999') {
        $data['expire_time'] = time() + (int) $data['expire'] * 86400;
      }
      if (!empty($data['_id'])) {
        $status = Db::connect('mongodb')->name('short_url')->where(['_id' => $data['_id']])->update($data);
        $tag = '编辑';
      } else {
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['_id'] = make_short_id($data['url'] . $this->uid . createId());
        $status = Db::connect('mongodb')->name('short_url')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    }
  }
  /**
   * 删除文章
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function delItem()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    $infoData = Db::connect('mongodb')->name('short_url')->where('_id', $data['id'])->find();
    if (empty($infoData)) {
      return Result::Error('内容不存在或已删除');
    }
    $status = Db::connect('mongodb')->name('short_url')->where('_id', $data['id'])->delete();
    Db::connect('mongodb')->name('short_url_log')->where('s_id', $data['id'])->delete();
    if ($status > 0) {
      return Result::Success('', '删除成功');
    } else {
      return Result::Error('删除失败，请稍后重试');
    }
  }
  public function del_item_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('short_url')->whereIn('_id', $data['id'])->delete();
    Db::connect('mongodb')->name('short_url_log')->whereIn('s_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function clear_sx_url()
  {
    $xsUrl = Db::connect('mongodb')->name('short_url')->field('_id')->where('expire', '<>', '99999')->where('expire_time', '<', time())->select();
    $ids = [];
    if (!empty($xsUrl)) {
      foreach ($xsUrl as $key => $vo) {
        $ids[] = $vo['_id'];
      }
    }
    if (!empty($ids)) {
      Db::connect('mongodb')->name('short_url_log')->whereIn('s_id', $ids)->delete();
      Db::connect('mongodb')->name('short_url')->whereIn('_id', $ids)->delete();
    }
    return json(['code' => 200, 'data' => $xsUrl, 'msg' => '清除成功']);
  }
  public function getAllUrl()
  {
    $where['uid'] = $this->uid;
    $dataList = Db::connect('mongodb')->name('short_url')->field('_id,title')->where($where)->order('create_time', 'desc')->select()->toArray();
    foreach ($dataList as $key => $vo) {
      $dataList[$key]['title'] = $vo['title'] . ':' . 'http://21ds.cn/u/'.$vo['_id'];
    }
    return Result::Success($dataList);
  }
  public function all_data()
  {
    $return['date'] = date('Y-m-d H:i:s', strtotime(date('Y-m-d')) - 1);
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      '_id' => input('param._id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    $whereTj[] = ['uid', '=', $this->uid];
    if (!empty($data['_id'])) {
      $whereTj[] = ['s_id', '=', $data['_id']];
    }
    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);
    if ($end_date == $start_date) {
      $cycle_type = 'hour';
      $cycle_num = 24;
    } else {
      $cycle_type = 'day';
      $cycle_num = ($end_date - $start_date) / 86400;
    }
    $end_date = $end_date + 86399;
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    $yestData = Db::connect('mongodb')->name('short_url_log')->where($whereTj)->select();
    if (!empty($yestData)) {
      $yestData = $yestData->toArray();
    }
    $serialData = [];
    for ($i = 0; $i < $cycle_num; $i++) {
      if ($cycle_type == 'hour') {
        $nowTime = $start_date + $i * 3600;
        $serialData[date('H', $nowTime) . ':00'] = [];
      } else {
        $nowTime = $start_date + $i * 86400;
        $serialData[date('Ymd', $nowTime)] = [];
      }
    }
    if ($cycle_type == 'day') {
      $serialData[date('Ymd', $end_date)] = [];
    }
    foreach ($yestData as $key => $vo) {
      if ($cycle_type == 'hour') {
        $serialData[$vo['only_hour']][] = $vo;
      } else {
        $serialData[$vo['date']][] = $vo;
      }
    }
    $chartData = [];
    $return['total']['uv'] = 0;
    $return['total']['pv'] = 0;
    $num_type = '总数';
    if (!empty($data['_id'])) {
      $num_type = '数';
    }
    foreach ($serialData as $key => $vo) {
      // 日
      if (strlen($key) == 8) {
        if (!isset($vo['pv'])) {
          $vo['pv'] = 0;
        }
        if (!isset($vo['uv'])) {
          $vo['uv'] = 0;
        }
        foreach ($vo as $key2 => $vo2) {
          if (!empty($vo2)) {
            $vo['pv'] = $vo['pv'] + $vo2['pv'];
            $vo['uv'] = $vo['uv'] + $vo2['uv'];
            $return['total']['uv'] = $return['total']['uv'] + $vo2['uv'];
            $return['total']['pv'] = $return['total']['pv'] + $vo2['pv'];
          }
        }
        $year = substr($key, 0, 4);
        $month = substr($key, 4, 2);
        $day = substr($key, -2, 2);
        $charItem['date'] = $year . '-' . $month . '-' . $day;
        $charItem['value'] = $vo['pv'];
        $charItem['category'] = '打开' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = $vo['uv'];
        $charItem['category'] = '打开独立用户' . $num_type;
        $chartData[] = $charItem;
      } else {
        // 时
        if (!isset($vo['pv'])) {
          $vo['pv'] = 0;
        }
        if (!isset($vo['uv'])) {
          $vo['uv'] = 0;
        }
        foreach ($vo as $key2 => $vo2) {
          if (!empty($vo2)) {
            $vo['uv'] = $vo['uv'] + $vo2['uv'];
            $vo['pv'] = $vo['pv'] + $vo2['pv'];
          }
        }
        $charItem['date'] = $key;
        $charItem['value'] = $vo['pv'];
        $charItem['category'] = '打开' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = $vo['uv'];
        $charItem['category'] = '打开独立用户' . $num_type;
        $chartData[] = $charItem;
        $return['total']['pv'] = $return['total']['pv'] + $vo['pv'];
        $return['total']['uv'] = $return['total']['uv'] + $vo['uv'];
        $chartData[] = $charItem;
      }
    }
    $return['chart'] = $chartData;
    return Result::Success($return);
  }
}
